$(function(){
	//设置右边宽度高度
	var bodyHeight = window.screen.availHeight-100;//$("body").height();
	var height = bodyHeight - 195;
	$("#pane_help_content,#pane_faq_content,#pane_download").height(bodyHeight-75);
	$("#div_zip").height(bodyHeight-75).css("line-height",(bodyHeight-75)+"px")
	.find("a").click(function(){
		if($(this).hasClass("zip")){
			$(this).removeClass("zip");
			$("#div_main_wrap").animate({"margin-left":"242px"},"fast");
			$("#div_right_wrap").animate({width:"250px"},"fast");
			$("#div_right").animate({width:"240px"},"fast");
			$("#div_zip").animate({"margin-left":"240px"},"fast");
			
		}else{
			$(this).addClass("zip");
			$("#div_main_wrap,#div_zip").animate({"margin-left":"0px"},"fast");
			$("#div_right_wrap").animate({width:"10px"},"fast");
			$("#div_right").animate({width:"0px"},"fast");
		}
	});
	$("#content_right > div,#div_callRecords").height(height);
	
	//导航栏事件
	$("#nav_menu li a, #drop_info li a").click(function(){
		if(this.id == "logOut"){
			ajax("logout",{
				success:function(){
					var cnc_last_account = $.cookie("cnc_last_account");
					if(cnc_last_account){
						cnc_last_account = eval("("+cnc_last_account+")");
						cnc_last_account.autoLogin = false;
						delete cnc_last_account.token;
						$.cookie("cnc_last_account", $.json2Str(cnc_last_account), { expires: 7 });
					}
					window.location.href = "login.html";
				}
			});
			return;
		}
		$("#drop_info li,#nav_set,#nav_menu li").removeClass("active");
		$(this).tab("show");
	}).on("shown.bs.tab",function(){
		$('body').mCustomScrollbar("update");
	});
	
	//右侧导航栏事件
	$("#nav_rightMenu li").click(function(){
		var index = $(this).attr("name");
		rightNavMove(index);
	});
	
	//通讯录切换事件
	$("#tip_orgUser,#tip_contactUser").click(function(){
		$("#tip_orgUser,#tip_contactUser").removeClass("active");
		$(this).addClass("active");
	});
	$("#tip_cogContact").click(function(){
		$("div.modal").modal({backdrop:"static"});
	});
	$("#pane_orgUserMan,#pane_contactUserMan").click(function(){
		$("#"+this.id+"_treeview").tab("show");
	}).on("shown.bs.tab",function(){
		$("#treeview_orgUserMan,#treeview_contactUserMan").editTreeview("checkScroll");
		$("#listview_orgUserMan,#listview_contactUserMan").editListview("checkScroll");
		
	});
	
	$("button[name='btn_editAdd']").click(function(){
		$($(this).attr("data-target")).editListview("edit");
	});
	$("button[name='btn_editDel']").click(function(){
		var target = $(this).attr("data-target");
		var itemids = [];
		var itemNames = [];
		$.each($(target+" input:checked"), function(){
			if(this.value && this.value != ""){
				itemids.push(this.value);
				itemNames.push(this.name);
			}
		});
		
		if(itemids.length > 0){
			itemids = itemids.join(",");
			
			$.conAlert({
				zIndex:9999,
				context:"是否将:<font color='#b94a48'>"+itemNames+"</font> 删除?",
				callback:function(confirm){
					if(confirm){
						if(target == "#listview_orgUserMan"){
							ajax("deleteStaff",{
								data:{
									contid:itemids
								},
								success:function(dataResult){
									var result = dataResult.executeResult;
									if(result.result){
										updateContactList();
									}
									$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
								}
							});
						}else{
							ajax("deleteLinkInfo",{
								data:{
									contid:itemids
								},
								success:function(dataResult){
									var result = dataResult.executeResult;
									if(result.result){
										updateContactList();
									}
									$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
								}
							});
						}
					}
				}
			});
		}else{
			$("#modal_userMan").proAlert({alert:"warning",msg:"请选择对象", delay:2000});
		}
	});
	
	$("#user_search").bind("keyup keypress", function(){
		if(this.value.length > 0){
			$("#btn_user_search").hide();
			$("#btn_user_search_close").show();
		}else{
			$("#btn_user_search").show();
			$("#btn_user_search_close").hide();
		}
	});
	
	$("#btn_user_search_close i").click(function(){
		$("#user_search").val("").catcomplete("close");
		$("#btn_user_search").show();
		$("#btn_user_search_close").hide();
	});
	
	//初始化通讯录列表
	ajax("getStaffList", {
		success:function(dataResult){
			var dataView = $.toDataView({
				dataResult:dataResult,
				groupId:"departId",
				groupName:"departName",
				itemId:"staffId",
				itemName:"staffName"
			});
			
			$("#treeview_orgUser").treeview({
				height:height-75,
				width:238,
				dataResult:dataView.dataTreeView,
				createItem:createTreeViewItem
			});
			updateOrgDropdown(dataView.dataTreeView);
			
			dataView.dataTreeView = [{
				groupId:"all",
				groupName:"全部用户",
				itemType:"all",
				items:dataView.dataListView
			}].concat(dataView.dataTreeView.concat({
				groupId:"edit",
				groupName:"部门名称",
				itemType:"edit",
				items:[]
			},{
				groupId:"add",
				groupName:"添加部门",
				itemType:"add",
				items:[]
			}));
			
			$("#treeview_orgUserMan").editTreeview({
				height:height-75,
				dataView:dataView,
				listTarget:"#listview_orgUserMan",
				module:[
					{key:"check",name:"<input type='checkbox' value=''/>",width:"4%"},
					{key:"itemName",name:"用户名",width:"20%"},
					{key:"mobileNum",name:"手机",width:"20%"},
					{key:"telNum",name:"固话",width:"20%"},
					{key:"ttNum",name:"TT",width:"20%"},
					{key:"oper",name:"",width:"12%"}
				],
				onEditComplete:function($this, result, type){
					if(type == "insert"){
						ajax("addDepart",{
							data:{
								departname:result.groupName,
								parentid:0
							},
							success:function(dataResult){
								var result = dataResult.executeResult;
								if(result.result){
									updateContactList();
								}
								$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
							}
						});
					}else{
						ajax("modifyDepart",{
							data:{
								departid:result.groupId,
								departname:result.groupName
							},
							success:function(dataResult){
								var result = dataResult.executeResult;
								if(result.result){
									updateContactList();
								}
								$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
							}
						});
					}
				},
				onDelComplete:function($this, result){
					ajax("deleteDepart",{
						data:{
							departid:result.groupId
						},
						success:function(dataResult){
							var result = dataResult.executeResult;
							if(result.result){
								updateContactList();
							}
							$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
						}
					});
				},
				onEditItemComplete:function($this, result, type){
					if(type == "insert"){
						ajax("addStaff",{
							data:{
								departid:result.groupId,
								staffname:result.itemName,
								mobilenum:result.mobileNum,
								telnum:result.telNum,
								ttnum:result.ttNum
							},
							success:function(dataResult){
								var result = dataResult.executeResult;
								if(result.result){
									updateContactList();
								}
								$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
							}
						});
					}else{
						ajax("modifyStaff",{
							data:{
								departid:result.groupId,
								staffid:result.itemId,
								staffname:result.itemName,
								mobilenum:result.mobileNum,
								telnum:result.telNum,
								ttnum:result.ttNum
							},
							success:function(dataResult){
								var result = dataResult.executeResult;
								if(result.result){
									updateContactList();
								}
								$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
							}
						});
					}
				},
				onDelItemComplete:function($this, result){
					ajax("deleteStaff",{
						data:{
							staffid:result.itemId
						},
						success:function(dataResult){
							var result = dataResult.executeResult;
							if(result.result){
								updateContactList();
							}
							$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
						}
					});
				}
			});
			
			ajax("getLinkInfoList", {
				param:dataView.dataSearchView,
				success:function(dataResult, param){
					
					var dataView = $.toDataView({
						dataResult:dataResult,
						groupId:"groupId",
						groupName:"groupName",
						itemId:"conId",
						itemName:"contName"
					});
					
					$("#treeview_contactUser").treeview({
						height:height-75,
						width:238,
						dataResult:dataView.dataTreeView,
						createItem:createTreeViewItem
					});
					
					updateContactDropdown(dataView.dataTreeView);
					
					dataView.dataTreeView = [{
						groupId:"all",
						groupName:"全部联系人",
						itemType:"all",
						items:dataView.dataListView
					}].concat(dataView.dataTreeView.concat({
						groupId:"edit",
						groupName:"分组名称",
						itemType:"edit",
						items:[]
					},{
						groupId:"add",
						groupName:"添加分组",
						itemType:"add",
						items:[]
					}));
					
					$("#treeview_contactUserMan").editTreeview({
						height:height-75,
						dataView:dataView,
						listTarget:"#listview_contactUserMan",
						module:[
							{key:"check",name:"<input type='checkbox' value=''/>",width:"4%"},
							{key:"itemName",name:"用户名",width:"20%"},
							{key:"mobileNum",name:"手机",width:"20%"},
							{key:"telNum",name:"固话",width:"20%"},
							{key:"ttNum",name:"TT",width:"20%"},
							{key:"oper",name:"",width:"12%"}
						],
						onEditComplete:function($this, result, type){
							if(type == "insert"){
								ajax("addLinkGroup",{
									data:{
										groupname:result.groupName
									},
									success:function(dataResult){
										var result = dataResult.executeResult;
										if(result.result){
											updateContactList();
										}
										$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
									}
								});
							}else{
								ajax("modifyLinkGroup",{
									data:{
										groupid:result.groupId,
										groupname:result.groupName
									},
									success:function(dataResult){
										var result = dataResult.executeResult;
										if(result.result){
											updateContactList();
										}
										$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
									}
								});
							}
						},
						onDelComplete:function($this, result){
							ajax("deleteLinkGroup",{
								data:{
									groupid:result.groupId
								},
								success:function(dataResult){
									var result = dataResult.executeResult;
									if(result.result){
										updateContactList();
									}
									$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
								}
							});
						},
						onEditItemComplete:function($this, result, type){
							if(type == "insert"){
								ajax("addLinkInfo",{
									data:{
										groupid:result.groupId,
										contname:result.itemName,
										mobilenum:result.mobileNum,
										telnum:result.telNum,
										ttnum:result.ttNum
									},
									success:function(dataResult){
										var result = dataResult.executeResult;
										if(result.result){
											updateContactList();
										}
										$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
									}
								});
							}else{
								ajax("modifyLinkInfo",{
									data:{
										groupid:result.groupId,
										contid:result.itemId,
										contname:result.itemName,
										mobilenum:result.mobileNum,
										telnum:result.telNum,
										ttnum:result.ttNum
									},
									success:function(dataResult){
										var result = dataResult.executeResult;
										if(result.result){
											updateContactList();
										}
										$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
									}
								});
							}
						},
						onDelItemComplete:function($this, result){
							ajax("deleteLinkInfo",{
								data:{
									contid:result.itemId
								},
								success:function(dataResult){
									var result = dataResult.executeResult;
									if(result.result){
										updateContactList();
									}
									$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
								}
							});
						}
						
					});
					var source = dataView.dataSearchView.concat(param);
					source.sort(function(o, p){
						var a, b;
						a = o["category"];
			            b = p["category"];
			            return a === b ? 0 : (a < b ? 1 : -1);
					});
					
					source.sort(function(o, p){
						var a, b;
						a = o["category"];
			            b = p["category"];
			            if(a === b && o.label === p.label && o.value === p.value){
			            	var n;
			            	n=source.indexOf(o); 
			            	source.splice(n,1);
			            }
			            return 0;
					});
					var filter = function(request, response){
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i");
				        response($.grep(source, function(value) {
				          return matcher.test(value.label) || matcher.test(value.value);
				        }));
				    };
					
					$("#user_search").catcomplete({
						delay: 0,
						source: filter,
						autoClose:false,
						appendTo: "#content_right",
						renderItem:function(ul, item) {
							var keyword = $("#user_search").val();
							var pop_number =  $("<div class='el-right'>"+
								"<button name='btn_launchConf' class='btn circle pop-number' title='发起会议'>"+
									"<i class='fa fa-home fa-lg pop-number'></i>"+
								"</button>"+
								"<button name='btn_launchCall' class='btn circle pop-number' title='发起呼叫'>"+
									"<i class='fa fa-phone fa-lg pop-number'></i>"+
								"</button>"+
							"</div>");
							pop_number.find("button").click(function(){
								item["itemName"] = item.label;
								item["number"] = item.value;
								$.popClick(this.name, item, "number");
								if(this.name == "btn_launchCall")
									$("#user_search").val("").catcomplete("close");
							});
							var face = "<div class='el-left' style='min-width:20px;'><i class='fa fa-user fa-lg normal fa-border treeItemHeard'></i></div> ";
							if(item.faceImage){
								face = "<img class='img-rounded' height='20' width='20' src='"+ item.faceImage +"'/> ";
							}
							var label = "<div style='width:70px;float:left;height:24px;line-height:24px' title='"+item.label+"' class='text-overflow'>"+ 
											face +item.label.replace(keyword,"<font color='red'>"+keyword+"</font>") +
										"</div>" + item.value.replace(keyword,"<font color='red'>"+keyword+"</font>");
							
							return $("<li>")
						    .attr("data-value", item.value)
						    .append($("<a>").append(label).append(pop_number))
						    .appendTo(ul);
						}
					});
					$("#text_callNumber").catcomplete({
						delay: 0,
						source: filter,
						appendTo: "#content_right",
						renderItem:function(ul, item) {
							var keyword = $("#text_callNumber").val();
							var face = "<div class='el-left' style='min-width:20px;'><i class='fa fa-user fa-lg normal fa-border treeItemHeard'></i></div> ";
							if(item.faceImage){
								face = "<img class='img-rounded' height='20' width='20' src='"+ item.faceImage +"'/> ";
							}
							var label = "<div style='width:100px;float:left;height:24px;line-height:24px' title='"+item.label+"' class='text-overflow'>"+ 
											face +item.label.replace(keyword,"<font color='red'>"+keyword+"</font>")+
										"</div>" + item.value.replace(keyword,"<font color='red'>"+keyword+"</font>");
							
							return $("<li>")
						    .attr("data-value", item.value)
						    .append($("<a>").append(label))
						    .appendTo(ul);
						}
					});
					
				}
			});
			
			
		}
	});
	
	
	
	//通讯录刷新事件
	$("#tip_refresh_contact").click(function(){
		if($("#tip_orgUser").hasClass("active")){
			$("#treeview_orgUser").treeview("loading");
		}else{
			$("#treeview_contactUser").treeview("loading");
		}
		updateContactList();
	});
	
	$("#tip_addContact").click(function(){
		if($(this).hasClass("open")){
			$("#contact_mobile,#contact_telephone,#contact_tt,#contact_name").val("");
			$(this).removeClass("open");
			$("#div_addContact").animate({"height":"0px","padding":"0px"});
		}else{
			var phone = $("#text_callNumber").val();
			var type = getPhoneType(phone);
			switch (type) {
			case 4:
				$("#contact_mobile").val(phone);
				break;
			case 3:
				$("#contact_telephone").val(phone);		
				break;
			case 2:
				$("#contact_tt").val(phone);
				break;
			default:
				$("#div_addContact").proAlert({alert:"danger",msg:"添加的号码有误", delay:2000});
				return;
				break;
			}
			$(this).addClass("open");
			$("#div_addContact").animate({"height":height+"px","padding":"19px"});
		}
	});
	
	$("#tip_balance").popover({
		html:true,
		title:"",
		placement:"bottom",
		trigger:"manual",
		container:"body",
		content:"企业余额:￥<span id='span_balance'>0.00</span>"
	}).click(function(){
		var popover =$("#tip_balance").data("bs.popover");
		if(!popover.$arrow || popover.$arrow.is(":hidden")){
			ajax("getOrgDetail",{
				success:function(dataResult){
					var result = dataResult.dataView.synergyUser[0];
					$("#tip_balance").attr('data-content',"企业余额:￥"+result.balance).popover("setContent").popover("show");
				}
			});
		}else{
			$("#tip_balance").popover("hide");
		}
	});
	
	$("#filter_contactUser,#filter_orgUser").keyup(function(){
		$($(this).attr("data-target")).editListview("filter",this.value);
	});
	
	$("*[id^='tip_'],*[name^='tip_']").tooltip({container: "body"});
	
	$("a[href='#pane_confList']").on('shown.bs.tab', function () {
		$("#conferenceList").confsList("checkScroll");
	});
	
	$("#drop_info a,#nav_menu a,#btn_download").click(function(){
		$("#tip_help").parent().removeClass("active");
		$("<a href='#div_body_wrap'></a>").tab("show");
	});
	$("#tip_help").click(function(){
		$("#drop_info li,#nav_menu li").removeClass("active");
		
	}).one("shown.bs.tab",function(){
		$("body").mCustomScrollbar("update");
		$("#pane_help_content").mCustomScrollbar("update");
	});
	
	$("a[href='#pane_conf']").click(function(){
		$("#tip_help, #nav_menu a").parent().removeClass("active");
		$("<a href='#div_body_wrap'></a>").tab("show");
		$("#nav_menu a[href='#pane_confList']").tab("show").parent().addClass("active");
	});
	
	//body滚动条
	$("body,#pane_help_content,#pane_faq_content,#pane_download").mCustomScrollbar({
		scrollInertia:0,
		advanced:{
			autoScrollOnFocus:false
		}
	});
	
});


var statusTimer = null;
var lastStatus = 0;

function rightNavMove(index){
	$("#user_search").val("").catcomplete("close");
	$("#nav_rightMenu li").removeClass("active").filter("[name='"+index+"']").addClass("active");
	var margin = index*-238;
	if ($.support.html5Clone){
		$("#content_right").css("margin-left",margin+"px");
	}else{
		$("#content_right").animate({"margin-left": margin+"px"}, 200);
	}
}

function updateOrgDropdown(data){
	$("#dropdown_orgUserMan").empty().html(genDropdownItem(data, "新建部门"))
	.find("li").click(function(){
		var $this = $(this);
		if($this.attr("name")=="edit"){
			$("#treeview_orgUserMan").editTreeview("edit");
		}else{
			var staffids = [];
			var staffNames = [];
			$.each($("#listview_orgUserMan input:checked"), function(){
				if(this.value && this.value != ""){
					staffids.push(this.value);
					staffNames.push(this.name);
				}
			});
			
			if(staffids.length > 0){
				staffids = staffids.join(",");
				
				$.conAlert({
					zIndex:9999,
					context:"是否将用户:<font color='#b94a48'>"+staffNames+"</font> 移动到 <font color='#31708f'>"+$this.text() +"</font>?",
					callback:function(confirm){
						if(confirm){
							ajax("modifyStaff",{
								data:{
									departid:$this.attr("name"),
									staffid:staffids,
									ismove:true
								},
								success:function(dataResult){
									var result = dataResult.executeResult;
									if(result.result){
										updateContactList();
									}
									$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
								}
							});
						}
					}
				});
			}else{
				$("#modal_userMan").proAlert({alert:"warning",msg:"请选择用户", delay:2000});
			}
		}
	});
}

function updateContactDropdown(data){
	$("#dropdown_contactUserMan").empty().html(genDropdownItem(data, "新建分组"))
	.find("li").click(function(){
		var $this = $(this);
		if($this.attr("name")=="edit"){
			$("#treeview_contactUserMan").editTreeview("edit");
		}else{
			var contids = [];
			var contNames = [];
			$.each($("#listview_contactUserMan input:checked"), function(){
				if(this.value && this.value != ""){
					contids.push(this.value);
					contNames.push(this.name);
				}
			});
			
			if(contids.length > 0){
				contids = contids.join(",");
				
				$.conAlert({
					zIndex:9999,
					context:"是否将联系人:<font color='#b94a48'>"+contNames+"</font> 移动到 <font color='#31708f'>"+$this.text() +"</font>?",
					callback:function(confirm){
						if(confirm){
							ajax("modifyLinkInfo",{
								data:{
									groupid:$this.attr("name"),
									contid:contids,
									mobilenum:"13888888888",
									ismove:true
								},
								success:function(dataResult){
									var result = dataResult.executeResult;
									if(result.result){
										updateContactList();
									}
									$("#modal_userMan").proAlert({alert:result.result?"success":"danger",msg:result.errorDescr, delay:2000});
								}
							});
						}
					}
				});
			}else{
				$("#modal_userMan").proAlert({alert:"warning",msg:"请选择联系人", delay:2000});
			}
		}
	});
	
	$("#div_addContact .dropdown-menu").empty().html(genDropdownItem(data, null))
	.find("li").click(function(){
		$("#contact_group").html($(this).text() +" <i class='caret'></i>").attr("name", $(this).attr("name"));
	});
}

function updateContactList(){
	ajax("getStaffList", {
		success:function(dataResult){
			var dataView = $.toDataView({
				dataResult:dataResult,
				groupId:"departId",
				groupName:"departName",
				itemId:"staffId",
				itemName:"staffName"
			});
			
			$("#treeview_orgUser").treeview("setData", dataView.dataTreeView);
			
			updateOrgDropdown(dataView.dataTreeView);
			
			dataView.dataTreeView = [{
				groupId:"all",
				groupName:"全部用户",
				itemType:"all",
				items:dataView.dataListView
			}].concat(dataView.dataTreeView.concat({
				groupId:"edit",
				groupName:"部门名称",
				itemType:"edit",
				items:[]
			},{
				groupId:"add",
				groupName:"添加部门",
				itemType:"add",
				items:[]
			}));
			$("#treeview_orgUserMan").editTreeview("setDataView", dataView);
			
			
			ajax("getLinkInfoList", {
				param:dataView.dataSearchView,
				success:function(dataResult, param){
					var dataView = $.toDataView({
						dataResult:dataResult,
						groupId:"groupId",
						groupName:"groupName",
						itemId:"conId",
						itemName:"contName"
					});
					
					$("#treeview_contactUser").treeview("setData", dataView.dataTreeView);
					
					updateContactDropdown(dataView.dataTreeView);
					
					dataView.dataTreeView = [{
						groupId:"all",
						groupName:"全部联系人",
						itemType:"all",
						items:dataView.dataListView
					}].concat(dataView.dataTreeView.concat({
						groupId:"edit",
						groupName:"分组名称",
						itemType:"edit",
						items:[]
					},{
						groupId:"add",
						groupName:"添加分组",
						itemType:"add",
						items:[]
					}));
					
					$("#treeview_contactUserMan").editTreeview("setDataView", dataView);
					
					var source = dataView.dataSearchView.concat(param);
					source.sort(function(o, p){
						var a, b;
						a = o["category"];
			            b = p["category"];
			            return a === b ? 0 : (a < b ? 1 : -1);
					});
					source.sort(function(o, p){
						var a, b;
						a = o["category"];
			            b = p["category"];
			            if(a === b && o.label === p.label && o.value === p.value){
			            	var n; 
			            	n=source.indexOf(o); 
			            	source.splice(n,1);
			            }
			            return 0;
					});
					
					$("#user_search,#text_callNumber").catcomplete("option", "source", function(request, response){
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i");
				        response($.grep(source, function(value) {
				          return matcher.test(value.label) || matcher.test(value.value);
				        }));
				    });
				    $("button[name='btn_editAdd']").addClass("disabled").css('visibility','hidden');
				}
			});
		}
	});
}


function genDropdownItem(result, addItemName){
	var items = "";
	for ( var key in result) {
		items +="<li name='"+result[key].groupId+"'><a href='#'>"+result[key].groupName+"</a></li>";
	}
	if(addItemName){
		items += "<li class='divider'></li>";
		items +="<li name='edit'><a href='#'><i class='fa fa-plus'></i> "+addItemName+"</a></li>";
	}
	return items;
}

//生成通讯录item样式
function createTreeViewItem($this, result){
	var pop_number =  "<div class='el-right'>"+
			"<button name='btn_launchConf' class='btn btn-warning circle pop-number' title='发起会议'>"+
				"<i class='fa fa-home fa-lg pop-number'></i>"+
			"</button>"+
			"<button name='btn_launchCall' class='btn btn-warning circle pop-number' title='发起呼叫'>"+
				"<i class='fa fa-phone fa-lg pop-number'></i>"+
			"</button>"+
		"</div>";
	var face = "<div class='el-left' style='margin-right:5px;min-width:20px'>" +
					"<i class='fa fa-user fa-lg normal fa-border treeItemHeard'></i>" +
					"<i class='fa fa-user active fa-border treeItemHeard' style='font-size:30px'></i>" +
				"</div> ";
	if(result.faceImage){
		face = "<img class='img-rounded' height='20' width='20' src='"+ result.faceImage +"'/> ";
	}
	var li = $("<tr><td class='list-group-item'> "+face+result.itemName+pop_number+"</td></tr>")
	.click(function(){
		$this.parent.container.find("table.listBody td.list-group-item.active").removeClass("active");
		$(this).find("td").addClass("active");
	}).data("cnc.user", result);
	
	li.find("div.el-right button").click(function(){
		$(this).addClass("active");
		if(result.telNum != "" || result.ttNum != ""){
			$.singlePop($("#div_numPop"), this, "fadeIn", result);
		}else{
			$.popClick(this.name, result, "mobileNum");
		}
	});
	return li;
}







/*

EditTreeView - jQuery EditTreeView Plugin
-----------------------------------------------

*/

(function($) {
	
	function EditTreeView(target, option) {
		this.container = $(target);
		this.options = option;
		this.groups = {};
		this.editTnit();
	};
	
	EditTreeView.prototype = $.extend({}, $.fn.treeview.Constructor.prototype);
	
	EditTreeView.prototype.editTnit = function(){
		var $this = this;
		$this.options.dataResult = $this.options.dataView.dataTreeView;
		$this.init();
		
		$($this.options.listTarget).editListview({
			height:$this.options.height,
			dataResult:$this.options.dataView.dataListView.concat({
				groupId:null,
				groupName:null,
				itemType:"edit"
			}),
			module:$this.options.module,
			onEditItemComplete:$this.options.onEditItemComplete,
			onDelItemComplete:$this.options.onDelItemComplete,
			filter:function(keyword, dataResult){
				if(!keyword || keyword =="")
					return dataResult;
				var filterResult = [];
				for(var key in dataResult){
					var result = dataResult[key];
					if(!result.itemType && (result.itemName.toLowerCase().indexOf(keyword.toLowerCase()) != -1 || result.mobileNum.indexOf(keyword) != -1
					|| result.telNum.indexOf(keyword) != -1 || result.telNum.indexOf(keyword) != -1)){
						filterResult.push(result);
					}
				}
				return filterResult;
			}
		});
	};
	
	EditTreeView.prototype.edit = function(){
		this.groups["edit"].show();
		this.checkScroll();
		this.scrollTo("bottom");
	};
	
	EditTreeView.prototype.setDataView = function(dataView){
		var $this = this;
		$this.setData(dataView.dataTreeView);
		$($this.options.listTarget).editListview("setData",dataView.dataListView.concat({
			itemType:"edit"
		}));
	};
	
	//联系人管理:生成通讯录group样式
	function createTreeViewHeard($this, group, result){
		var groupHeard = $("<a class='list-group-item "+(result.itemType == "all"?"active":"")+"' />");
		var edit = $("<div class='input-group'>" +
						"<input class='form-control' maxlength='10' placeholder='"+result.groupName+"' />" +
						"<span style='display: table-cell;vertical-align: middle'>"+
							"<button name='ok' class='btn btn-success'>" +
								"<i class='fa fa-check'></i>" +
							"</button>" +
						"</span>"+
						"<span style='display: table-cell;vertical-align: middle'>"+
							"<button name='cancel' class='btn btn-info'>" +
								"<i class='fa fa-mail-reply'></i>" +
							"</button>" +
						"</span>"+
					"</div>");
		
		if(result.itemType == "add"){
			var addBtn = $("<button class='btn btn-success' style='width:100%;padding:10px 5px'>" +
								"<i class='fa fa-plus'/> "+result.groupName +
							"</button>")
			.click(function(){
				$this.groups["edit"].show();
			});
			groupHeard.css("padding","0").html(addBtn);
		}else if(result.itemType =="edit"){
			edit.find("button").click(function(){
				if(this.name=="ok"){
					$this.options.onEditComplete($this, {
						groupName:edit.find(":text").val()
					}, "insert");
				}
				edit.find(":text").val("");
				group.hide();
				$this.checkScroll();
			});
			groupHeard.css("padding","2").html(edit);
			group.hide();
		}else{
			var groupItem = $("<div name='display' title='"+ result.groupName +"'>" +
								"<div class='text-overflow' style='max-width:120px;float:left'>"+result.groupName +"</div> ["+result.items.length+"]" +
							"</div>");
			
			if(result.itemType != "all"){
				var dropdown = $("<span class='dropdown'>" +
									"<span class='badge btn-default' data-toggle='dropdown'><i class='fa fa-caret-down'></i></span>" +
									"<ul class='dropdown-menu pull-right' >" +
										"<li><a name='reName' tabindex='-1' href='#'>重命名分组</a></li>" +
										"<li><a name='del' tabindex='-1' href='#'>删除分组</a></li>" +
									"</ul>" +
								"</span>");

				dropdown.find("a").click(function(){
					if(this.name == "reName"){
						groupHeard.css("padding","2").find("div[name='display']").hide();
						edit.show().find(":text").val(result.groupName);
					}else{
						$.conAlert({
							zIndex:9999,
							context:"是否确定将分组:<font color='#b94a48'>"+result.groupName+"</font>删除?",
							callback:function(confirm){
								if(confirm){
									$this.options.onDelComplete($this, result);
								}
							}
						});
					}
				});
				groupItem.append(dropdown);
			}
			
			edit.hide().find("button").click(function(){
				if(this.name=="ok"){
					$this.options.onEditComplete($this, {
						groupId:result.groupId,
						groupName:edit.find(":text").val()
					}, "modify");
				}
				groupHeard.css("padding","10px 15px").find("div[name='display']").show();
				edit.hide();
			});
			
			groupHeard.append(edit).append(groupItem)
			.click(function(){
				if(result.itemType == "all"){
					if($this.container[0].id == "treeview_orgUserMan"){
						$("#btn_org_editAdd").css('visibility','hidden').addClass('disabled');
					}
					if($this.container[0].id == "treeview_contactUserMan"){
						$("#btn_contact_editAdd").css('visibility','hidden').addClass('disabled');
					}
				}else{
					if($this.container[0].id == "treeview_orgUserMan"){
						$("#btn_org_editAdd").css('visibility','visible').removeClass('disabled');
					}
					if($this.container[0].id == "treeview_contactUserMan"){
						$("#btn_contact_editAdd").css('visibility','visible').removeClass('disabled');
					}
				}
				$this.container.find("a.list-group-item").removeClass("active");
				$(this).addClass("active");
				$($this.options.listTarget).listview("setData",
					result.items.concat({
						groupId:result.groupId,
						groupName:result.groupName,
						itemType:"edit"
					})
				);
				$($this.options.dropdownTarget).find("li").removeClass("disabled").filter("[name='"+result.groupId+"']").addClass("disabled");
				$($this.options.listTarget).find(".listHeard :checkbox")[0].checked=false;
			});
			
		}
		
		return groupHeard;
	}

	$.fn.editTreeview = function(option, param) {
		EditTreeView.defaultOption = $.extend({} , $.fn.treeview.Constructor.defaultOption, {
			listTarget:"",
			module:[],
			createHeard:createTreeViewHeard,
			onEditComplete:function($this, result, type){},
			onDelComplete:function($this, result){}
		});
		 
		return this.each(function() {
			var $this   = $(this);
			var data    = $this.data('cnc.editTreeview');
			var options = typeof option == 'object' && option;

			options = $.extend({}, EditTreeView.defaultOption, $this.data(), options);
			
			if (!data) $this.data('cnc.editTreeview', (data = new EditTreeView(this, options)));
			if (typeof option == 'string') data[option](param);
		});
	};
})(jQuery);
/*

EditListView - jQuery EditListView Plugin
-----------------------------------------------

*/

(function($) {
	function EditListView(target, option) {
		this.options = option;
		this.container = $(target);
		this.editTnit();
	};
	
	EditListView.prototype = $.extend({}, $.fn.listview.Constructor.prototype);
	
	EditListView.prototype.editTnit = function(){
		var $this = this;
		$this.init();
	};
	
	EditListView.prototype.edit = function(){
		this.listBody.find("tr.edit,tr.edit .add").show();
		this.listBody.find("tr.edit .modify").hide();
		this.checkScroll();
		this.scrollTo("bottom");
	};
	
	//联系人管理:生成元素
	function createListViewItem($this, result){
		var item = "<tr "+(result.itemType == "edit"?"class='edit' style='display:none'":"")+">";
		
		for ( var key in $this.options.module) {
			var m =  $this.options.module[key];
			if(m.key == "check"){
				item += "<td width='"+m.width +"'>" +
							"<input name='"+(result.itemName?result.itemName:"")+"' type='checkbox' value='"+ (result.itemId?result.itemId:"")+"'/>" +
						"</td>";
				continue;
			}
			if(m.key == "oper"){
				item += "<td name ='"+m.key+"' width='"+m.width +"'>" +
							"<div class='listview_text' "+(result.itemType == "edit"?"style='display:none'":"")+" >" +
								"<button name='edit' title='修改' class='btn btn-warning btn-xs btn-edit'><i class='fa fa-edit'></i></button> " +
								"<button name='delete' title='删除' class='btn btn-danger btn-xs btn-edit'><i class='fa fa-trash-o'></i></button>" +
							"</div>" +
							"<div class='listview_editText' "+(result.itemType == "edit"?"":"style='display:none'")+" >"+
								"<button name='save' title='保存' class='btn btn-success btn-xs btn-edit'><i class='fa fa-save'></i></button> " +
								"<button name='cancel' title='撤销' class='btn btn-info btn-xs btn-edit'><i class='fa fa-reply'></i></button>" +
							"</div>" +
						"</td>";
				continue;
			}
			
			
			if(m.key == "mobileNum" && $this.container.attr("id")=="listview_orgUserMan"){
				item += "<td name ='"+m.key+"' width='"+m.width +"'>" +
				"<span class='listview_editText modify' "+(result.itemType == "edit"?"style='display:none'":"")+">"+result[m.key]+"</span>"+
				"<input name='"+m.key+"' class='form-control listview_text add' maxlength='15' "+(result.itemType == "edit"?"":"style='display:none' value='"+result[m.key]+"'")+">" +
			    "</td>";
				continue;
				
			}
			item += "<td name ='"+m.key+"' width='"+m.width +"'>" +
						"<span class='listview_text' "+(result.itemType == "edit"?"style='display:none'":"")+">"+result[m.key]+"</span>"+
						"<input name='"+m.key+"' class='form-control listview_editText' maxlength='15' "+(result.itemType == "edit"?"":"style='display:none' value='"+result[m.key]+"'")+">" +
					"</td>";
		}
		item += "</tr>";
		item = $(item);
		item.click(function(){
			$this.listBody.find("tr.edit").removeClass("warning").find(":checkbox")[0].checked = false;
			if(item.edit)
				return;
			if($(this).hasClass("warning") && !$(this).hasClass("edit")){
				$(this).removeClass("warning").find(":checkbox")[0].checked = false;
				$this.listHeard.find(":checkbox")[0].checked = false;
			} else {
				$(this).addClass("warning").find(":checkbox")[0].checked = true;
			}
		}).find("button.btn-edit").click(function(e){
			e.stopPropagation();
			switch (this.name) {
			case "edit":
				$.each(item.find(":text"), function(){
					this.value = result[this.name];
				});
				item.edit = true;
				item.addClass("warning").find(":checkbox")[0].checked = true;
				item.find("*.listview_text ").hide();
				item.find("*.listview_editText").show();
				break;
			case "delete":
				$.conAlert({
					zIndex:9999,
					context:"是否确定将用户:<font color='#b94a48'>"+result.itemName+"</font>删除?",
					callback:function(confirm){
						if(confirm){
							$this.options.onDelItemComplete($this, result);
						}
					}
				});
				break;
			case "save":
				var paramResult = $.extend({}, result);
				$.each(item.find(":input"), function(){
					paramResult[this.name] = this.value;
				});
				
				if(paramResult.itemName == "" || paramResult.mobileNum == ""){
					if($this.container.attr("id") == "listview_orgUserMan"){
						$("#listview_orgUserMan").proAlert({alert:"danger",msg:"用户名和手机为必填项", delay:2000});
					}
					if($this.container.attr("id") == "listview_contactUserMan"){
						$("#listview_contactUserMan").proAlert({alert:"danger",msg:"用户名和手机名为必填项", delay:2000});
					}
						return;
				}
				
			   if(getPhoneType(paramResult.mobileNum) != 4){
				   if($this.container.attr("id") == "listview_orgUserMan"){
						$("#listview_orgUserMan").proAlert({alert:"danger",msg:"请输入正确的手机格式", delay:2000});
					}
					if($this.container.attr("id") == "listview_contactUserMan"){
						$("#listview_contactUserMan").proAlert({alert:"danger",msg:"请输入正确的手机格式", delay:2000});
					}
						return;
			   }
			   
			   if(getPhoneType(paramResult.telNum) != 3){
				   if(paramResult.telNum != ""){ 
				   if($this.container.attr("id") == "listview_orgUserMan"){
						$("#listview_orgUserMan").proAlert({alert:"danger",msg:"固话格式错误，正确格式区号+固话：例如07551234567", delay:5000});
					}
					if($this.container.attr("id") == "listview_contactUserMan"){
						$("#listview_contactUserMan").proAlert({alert:"danger",msg:"固话格式错误，正确格式区号+固话：例如07551234567", delay:5000});
					}
						return;
				   }
			   }
	
			   if(getPhoneType(paramResult.ttNum) != 2){
				   if(paramResult.ttNum != ""){
					   if($this.container.attr("id") == "listview_orgUserMan"){
						   $("#listview_orgUserMan").proAlert({alert:"danger",msg:"请输入正确的TT号格式", delay:2000});
					   }
					   if($this.container.attr("id") == "listview_contactUserMan"){
						   $("#listview_contactUserMan").proAlert({alert:"danger",msg:"请输入正确的TT号格式", delay:2000});
					   }
					   	return;
				   }
			   }
				
				if(result.itemType == "edit"){
					$this.options.onEditItemComplete($this, paramResult, "insert");
				}else{
					$.conAlert({
						zIndex:9999,
						context:"是否保存对用户:<font color='#b94a48'>"+result.itemName+"</font>的修改?",
						callback:function(confirm){
							if(confirm){
								$this.options.onEditItemComplete($this, paramResult, "modify");
								item.edit = false;
								item.find("*.listview_text").show();
								item.find("*.listview_editText").hide();
								item.removeClass("warning").find(":checkbox")[0].checked = false;
							}
						}
					});
				}
				
				break;
			case "cancel":
				if(result.itemType == "edit"){
					item.hide();
				}else{
					item.edit = false;
					item.find("*.listview_text").show();
					item.find("*.listview_editText").hide();
					item.removeClass("warning").find(":checkbox")[0].checked = false;
				}
				break;
			}
			$this.checkScroll();
		});
		return item;
	}
	
	function onHeardClick(event){
		if(event.target.type == "checkbox"){
			$.each(event.data.listBody.find(":checkbox"), function(){
				this.checked = event.target.checked;
				if(this.checked){
					event.data.listBody.find("tr").addClass("warning");
				}else{
					event.data.listBody.find("tr").removeClass("warning");
				}
			});
		}
	}
	
	$.fn.editListview = function(option, param) {
		EditListView.defaultOption = $.extend({} , $.fn.listview.Constructor.defaultOption, {
			createItem:createListViewItem,
			onHeardClick:onHeardClick,
			onEditItemComplete:function($this, result, type){},
			onDelItemComplete:function($this, result){}
		});
		 
		return this.each(function() {
			var $this   = $(this);
			var data    = $this.data('cnc.listview');
			var options = typeof option == 'object' && option;
			
			options = $.extend({}, EditListView.defaultOption, $this.data(), options);
			
			if (!data) $this.data('cnc.listview', (data = new EditListView(this, options)));
			if (typeof option == 'string') data[option](param);
		});
	};
})(jQuery);
